package com.fishery.authority.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.authority.entity.*;
import com.fishery.authority.entity.dto.UserModifiedDto;
import com.fishery.authority.entity.vo.*;
import com.fishery.authority.mapper.RoleMapper;
import com.fishery.authority.mapper.UserMapper;
import com.fishery.authority.service.*;
import com.fishery.authority.utils.*;
import com.fishery.entity.GlobalException;
import com.fishery.entity.Result;
import com.fishery.entity.StatusCode;
import com.fishery.util.MD5;
import com.fishery.util.TokenManager;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 711
 * @since 2021-01-13
 */
@RestController
@CrossOrigin
@RequestMapping("/authority/user")
@Api("用户中心，包括登录注册")
public class UserController {

    @Value(value = "${user.default.avatar}")
    private String DefaultAvatar;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册接口
     *
     * @param userVo
     * @return
     */
    @ApiOperation("注册新用户")
    @PostMapping("/register")
    public Result registerNewUser(UserVo userVo) {
        return userService.register(userVo);
    }

    /**
     * 手机账号密码登陆
     *
     * @param user
     * @param request
     * @param code
     * @param response
     * @return
     */
    @ApiOperation("手机账号密码登陆接口")
    @PostMapping(value = "/login")
    public Result login(UserLoginPassword user,
                        HttpServletRequest request,
                        String code,
                        HttpServletResponse response) {
        String ipAdrress = IpAddressUtil.getIpAdrress(request);
        if (code == null) {
            return new Result(false, StatusCode.LOGINERROR, "验证码为空", "请输入验证码");
        }
        if(!captchaService.checkVerificationCode(request, code)) {
            return new Result(false, StatusCode.LOGINERROR, "验证码错误", "请重新输入");
        }
        if(user.getPhone() == null || user.getPassword() == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败，账号或密码为空", "请输入账号密码");
        }
        User ifNull = userMapper.selectByPhone(user.getPhone());
        if(ifNull == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败，未注册", "请先注册");
        }
        User userLogin = userService.loginByPassword(user);
        User userDouble = userService.getById(userLogin.getId());
        if(!MD5.encrypt(user.getPassword()).equals(userDouble.getPassword())) {
            return new Result(false, StatusCode.ERROR, "登陆失败，密码错误", "请重新输入");
        }
        UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userLogin;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userDouble.getId());
        UserRole userRole = userRoleService.getOne(wrapper);
//        List<Role> roles = roleMapper.findByUserId(userLogin.getId());
        String roleName = roleMapper.findRoleNameByUserId(userLogin.getId());
        // 将用户信息封装到一个map集合返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("id", userLogin.getId());
        map.put("userName", userLogin.getUsername());
        map.put("avatar", userDouble.getAvatar());
//        map.put("role",roles.get(0).getName());
        map.put("email", userDouble.getEmail());
        map.put("role",roleName);
        map.put("roleId", userRole.getRoleId());
        map.put("theme", userDouble.getTheme());
        map.put("phone", userLogin.getPhone());
        map.put("baseId", userDetailsImpl.getBaseId());
        map.put("baseIdentity", userDetailsImpl.getBaseIdentity());
        Collection<? extends GrantedAuthority> authorities = userDetailsImpl.getAuthorities();
        String token =
                tokenManager.createToken(
                        userLogin.getId(),
                        userLogin.getUsername(),
                        userLogin.getBaseIdentity(),
                        userLogin.getBaseId(),
                        (Collection<GrantedAuthority>) authorities);
        ResponseUtil.placeToken(response, token);
        return new Result(true, StatusCode.OK, "登陆成功", map);
    }

    /**
     * 手机验证码登陆
     *
     * @param userLoginVo
     * @param response
     * @return
     */
    @ApiOperation("手机验证码登陆接口")
    @PostMapping(value = "/loginByPhone")
    public Result loginByPhone(UserLoginVo userLoginVo,
                               HttpServletResponse response) {
        if(userLoginVo.getCode() == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败，验证码为空", "请输入验证码");
        }
        User userLogin = userService.loginByVerification(userLoginVo);
        User userDouble = userService.getById(userLogin.getId());
        UserDetailsImpl userDetailsImpl = (UserDetailsImpl) userLogin;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userDouble.getId());
        UserRole userRole = userRoleService.getOne(wrapper);
        // 将用户信息封装到一个map集合返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("id", userLogin.getId());
        map.put("userName", userLogin.getUsername());
        String roleName = roleMapper.findRoleNameByUserId(userLogin.getId());
        map.put("avatar", userDouble.getAvatar());
        map.put("role",roleName);
        map.put("roleId", userRole.getRoleId());
        map.put("theme", userDouble.getTheme());
        map.put("email", userDouble.getEmail());
        map.put("phone", userLogin.getPhone());
        map.put("baseId", userDetailsImpl.getBaseId());
        map.put("baseIdentity", userDetailsImpl.getBaseIdentity());
        Collection<? extends GrantedAuthority> authorities = userDetailsImpl.getAuthorities();
        String token = tokenManager.createToken(userLogin.getId(),
                userLogin.getUsername(),
                userLogin.getBaseIdentity(),
                userLogin.getBaseId(),
                (Collection<GrantedAuthority>) authorities);
        ResponseUtil.placeToken(response, token);
        return new Result(true, StatusCode.OK, "登陆成功", map);
    }

    /**
     * 根据ID查询用户
     *
     * @param id ID
     * @return
     */
    @ApiImplicitParam(paramType = "path", name = "id", value = "登录ID", required = true, dataType = "String")
    @ApiOperation("根据id查询普通用户接口")
    //鉴权，有authority权限才给执行
//    @PreAuthorize("hasAnyAuthority('authority')")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findByUserId(id));
    }

    /**
     * 用户查看自己信息接口
     */
    @ApiOperation("用户查询自己信息接口")
    @RequestMapping(value = "/self", method = RequestMethod.GET)
    public Result findSelf() {
        // 从安全中获取用户的信息
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
        String userId = user.getId();
        User userNew = userService.findByUserId(userId);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        UserRole userRole = userRoleService.getOne(wrapper);
        String roleId = userRole.getRoleId();
        Role role = roleService.getById(roleId);
        UserRoleVo userRoleVo = new UserRoleVo();
        userRoleVo.setRoleId(roleId);
        userRoleVo.setRoleName(role.getName());
        userRoleVo.setAvatar(userNew.getAvatar());
        userRoleVo.setBaseId(userNew.getBaseId());
        userRoleVo.setBaseIdentity(userNew.getBaseIdentity());
        userRoleVo.setEmail(userNew.getEmail());
        userRoleVo.setId(userId);
        userRoleVo.setIsAdmin(userNew.getIsAdmin());
        userRoleVo.setPhone(userNew.getPhone());
        userRoleVo.setTheme(userNew.getTheme());
        userRoleVo.setUsername(userNew.getUsername());
        return new Result(true, StatusCode.OK, "查询成功", userRoleVo);
    }

    /**
     * 修改
     *
     * @param userModifiedDto
     */
    @ApiOperation("用户修改自己接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", required = true, dataType = "String"),
//    })
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public Result update(@RequestBody UserModifiedDto userModifiedDto) {
//        @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
//    public Result update(@RequestBody User user, @PathVariable String id) {
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();

//        if (!id.equals(userDetails.getId())) {
//            return Result.error("用户只能修改自己的信息");
//        }

        //防止用户非法修改账号
        User loginUser = userService.findByUserId(userDetails.getId());
//        user.setBaseId(loginUser.getBaseId());
//        user.setBaseIdentity(loginUser.getBaseIdentity());
//        user.setPassword(loginUser.getPassword());
//        user.setIsAdmin(loginUser.getIsAdmin());
//        user.setId(userDetails.getId());
//        userModifiedDto.setId(loginUser.getId());
//        userService.updateUser(loginUser);
        if(userModifiedDto.getAvatar() != null) {
            loginUser.setAvatar(userModifiedDto.getAvatar());
        }
        if(userModifiedDto.getEmail() != null) {
            loginUser.setEmail(userModifiedDto.getEmail());
        }
        if(userModifiedDto.getPhone() != null) {
            loginUser.setPhone(userModifiedDto.getPhone());
        }
        if(userModifiedDto.getUsername() != null) {
            loginUser.setUsername(userModifiedDto.getUsername());
        }
        if(!StringUtils.isEmpty(userModifiedDto.getTheme())) {
            loginUser.setTheme(userModifiedDto.getTheme());
        }
        boolean ret = userService.updateById(loginUser);
        return ret? Result.success("修改成功") : Result.error("修改失败");
    }

    /**
     * 找回密码
     *
     * @param code
     * @param user
     * @return
     */
    @ApiOperation("找回密码接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "code", value = "验证码", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "body", name = "user", value = "{\n" +
//                    "  \"password\": \"123456\"\n" +
//                    "  \"phone\": \"123456\"\n" +
//                    "}", required = true, dataType = "User")
//    })
    @RequestMapping(value = "/retrievePassword/{code}", method = RequestMethod.POST)
    public Result retrievePassword(@PathVariable String code,
                                   @RequestBody User user) {

        if (code == null) {
            return new Result(false, StatusCode.LOGINERROR, "登录失败，验证码为空", "请输入验证码");
        }
        userService.findPassword(user, code);
        return Result.success("修改成功");
    }

//    /**
//     * 用户申请变更基地管理员权限
//     *
//     * @param baseId
//     * @return
//     */
//    @ApiOperation("用户申请变更基地管理员权限")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "baseId", value = "基地id", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "path", name = "baseIdentity", value = "权限", dataType = "Integer")
//    })
//    @RequestMapping(value = "/applyFor/{baseId}/{baseIdentity}", method = RequestMethod.PUT)
//    public Result applyForBaseAdmin(@PathVariable String baseId, @PathVariable Integer baseIdentity) {
//        if (baseIdentity != 0 && baseIdentity != 1) {
//            return Result.error("权限错误");
//        }
//        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
//        userService.applyForBaseAdmin(user.getId(), baseId, baseIdentity);
//        return Result.success("申请成功");
//    }

    /**
     * 用户查看申请变更基地管理员的处理状态
     *
     * @return
     */
    @ApiOperation("用户查看申请变更基地管理员的处理状态")
    @RequestMapping(value = "/applyFor", method = RequestMethod.GET)
    public Result applyForStatus() {
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
        Map<String, String> map = userService.applyForStatus(user.getId());
        if (map == null) {
            return Result.success("已处理");
        } else {
            return new Result(true, StatusCode.OK, "未处理", map);
        }
    }


//    /**
//     * 用户查看申请新建基地的处理状态
//     *
//     * @return
//     */
//    @ApiOperation("用户查看申请新建基地的处理状态")
//    @RequestMapping(value = "applyFor/addBase/status", method = RequestMethod.GET)
//    public Result applyForAddBaseStatus() {
//        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
//        Base base = userService.applyForAddBaseStatus(user.getId());
//        if (base == null) {
//            String baseId = userService.getBase(user.getId()).get("baseId");
//            Object base1 = traceabilityClient.getBase(baseId).getData();
//            return new Result(true, StatusCode.OK, base1 == null ? "拒绝" : "同意", base1);
//        } else {
//            return new Result(true, StatusCode.OK, "未处理", base);
//        }
//    }

    @ApiOperation(value = "用户获取自己的基地身份")
    @RequestMapping(value = "/getBase", method = RequestMethod.GET)
    public Result getBaseIdentity() {
        UserDetailsImpl user = SecurityContextUtil.getUserDetails();
        HashMap<String, Object> base = userService.getBase(user.getId());
        if (base == null || "".equals(base)) {
            return new Result(false, StatusCode.ERROR, "用户基地信息为空", null);
        } else {
            return new Result(true, StatusCode.OK, "查询成功", base);
        }
    }

    /**
     * 基地管理人员邀请用户进基地
     *
     * @param userId
     * @return
     */
    @ApiOperation("邀请还没有进基地的用户进入基地")
    @GetMapping("/invite/{userId}")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result inviteUser(@ApiParam(value = "UserID", required = true)
                                 @PathVariable(name = "userId") String userId) {
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        String baseId = userService.findByUserId(userDetails.getId()).getBaseId();
        User user = userService.getById(userId);
        if(!StringUtils.isEmpty(user.getBaseId())) {
            return Result.error("该用户已有基地");
        }
        userService.inviteUserIntoBase(userId, baseId);
        return Result.success("发送邀请成功");
    }

    /**
     * 基地分页获取所有已邀请过的用户记录
     * 显示三种状态，待确认(2)，已拒绝(0)，已同意(1)
     *
     * @return
     */
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "current", value = "页面", dataType = "Integer"),
//            @ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
//    })
    @ApiOperation("基地分页查询已邀请的用户的结果,（通过status来判断，0表示已拒绝，1表示已同意，2表示待确认）")
    @GetMapping("/getUserInvited/{current}/{size}")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result getAllUserInvited(@PathVariable(name = "current") Integer current,
                                    @PathVariable(name = "size") Integer size) {
        size = size <= 0 ? 5 : size;
        current = current <= 0 ? 1 : current;
        String userId = SecurityContextUtil.getUserDetails().getId();
        String baseId = userService.findByUserId(userId).getBaseId();
        List<InvitationVo> invitationVoList = userService.getInvitationRecord(baseId);
        PageResult<InvitationVo> pageResult = PageUtil.getPage(invitationVoList, current, size);
        return Result.success("查询成功");
    }

    /**
     * 基地分页获取指定状态的邀请记录
     *
     * @param typeId
     * @return
     */
    @ApiOperation("基地分页获取指定状态的邀请记录")
    @GetMapping("/getTypeInvitation/{typeId}/{page}/{size}")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "typeId", value = "邀请状态类型ID", dataType = "String", required = true),
//            @ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer", required = true),
//            @ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer", required = true)
//    })
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result getUserInvitedByTypeId(@PathVariable(name = "typeId", required = true) String typeId, @PathVariable(name = "page", required = true) Integer page, @PathVariable(name = "size", required = true) Integer size) {
        if (StringUtils.isEmpty(typeId)
                || (!typeId.equals("2")
                && !typeId.equals("1")
                && !typeId.equals("0"))) {
            return Result.error("传入的typeId有误");
        }
        String userId = SecurityContextUtil.getUserDetails().getId();
        String baseId = userService.findByUserId(userId).getBaseId();
        List<User> typeInvitationRecord = userService.getTypeInvitationRecord(baseId, typeId);
        PageResult<User> pageResult = (PageResult<User>) PageUtil.getPage(typeInvitationRecord, page, size);
        return Result.success("查询成功").data(pageResult);
    }

    /**
     * 用户分页查看自己被哪些基地邀请
     *
     * @return
     */
    @ApiOperation("用户分页查看自己被哪些基地邀请")
    @GetMapping("/invitation/{page}/{size}")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
//            @ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
//    })
    public Result findAllInvitation(@PathVariable(name = "page") Integer page, @PathVariable(name = "size") Integer size) {
        // 获取当前用户的信息，主要为了后续获取userId
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        // 通过loginId获取用户被哪些基地邀请
        List<Map<String, String>> baseInfoList = userService.findAllInvitation(userDetails.getId());
        PageResult<Map<String, String>> pageResult = PageUtil.getPage(baseInfoList, page, size);
        return Result.success("查询成功").data(pageResult);
    }

    /**
     * 用户同意（拒绝）进某个基地
     * 同意（1），拒绝（0）
     *
     * @param selection
     * @param baseId
     * @return
     */
    @ApiOperation("用户同意（拒绝）进某个基地")
    @PutMapping("/invitation/{baseId}/{selection}")
    public Result executeSelection(@ApiParam(value = "同意（1），拒绝（0）", required = true) @PathVariable(name = "selection") String selection,
                                   @ApiParam(value = "基地ID", required = true) @PathVariable(name = "baseId") String baseId) {
        if (!"0".equals(selection) && !"1".equals(selection)) {
            return Result.error(StatusCode.ERROR, "选择无效");
        }
        // 获取当前用户
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        // 通过loginId、baseId、selection来进行执行这个选择
        userService.executeSelection(userDetails.getId(), baseId, selection);
        if (selection.equals("1")) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userDetails.getId());
            userRole.setRoleId("1356853657858");
            boolean save = userRoleService.save(userRole);
            if(!save) {
                return Result.error("绑定用户权限失败");
            }
        }
        return Result.success("选择成功");
    }

    /**
     * 基地删除所有的邀请记录（包含待确认、同意、拒绝）
     *
     * @return
     */
    @ApiOperation("基地删除所有邀请记录（包含待确认、同意、拒绝）")
    @DeleteMapping("/deleteInvitationRecord")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result deleteInvitationRecord() {
        String userId = SecurityContextUtil.getUserDetails().getId();
        String baseId = userService.findByUserId(userId).getBaseId();
        userService.deleteInvitationRecordByBaseId(baseId);
        return Result.success("删除成功");
    }

    //删除指定邀请记录
    @ApiOperation("删除指定邀请记录")
    @DeleteMapping("/deleteSpecialInvitation/{userId}/{baseId}/{typeId}")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result deleteSpecialInvitation(@ApiParam(name = "baseId", value = "用户id", required = true)
                                              @PathVariable(name = "baseId", required = true)
                                                      String baseId,
                                          @ApiParam(name = "userId", value = "用户id", required = true)
                                              @PathVariable(name = "userId", required = true)
                                                      String userId,
                                          @ApiParam(name = "typeId", value = "（2）待确认，（1）同意，（0）拒绝", required = true)
                                              @PathVariable(name = "typeId", required = true)
                                                      String typeId) {
        if (!typeId.equals("1") && !typeId.equals("2") && !typeId.equals("0")) {
            return Result.error("邀请类型有误，应为0、1、2");
        }
        User user_find = userService.getById(userId);
        if (user_find == null) {
            return Result.error("该用户不存在");
        }
        if (!StringUtils.isEmpty(user_find.getBaseId())) {
            return Result.error("该用户已有基地");
        }
        userService.deleteInvitationRecordByUserId(userId, baseId, typeId);
        return Result.success();
    }


    /**
     * 基地删除指定类型的邀请记录
     * 三种类型：同意、拒绝、待确认
     *
     * @param typeId
     * @return
     */
    @ApiOperation("基地删除指定类型的邀请记录")
    @DeleteMapping("/deleteInvitationRecord/{typeId}")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result deleteTypeInvitationRecord(@ApiParam(name = "typeId", value = "（2）待确认，（1）同意，（0）拒绝", required = true) @PathVariable(name = "typeId", required = true) String typeId) {
        String userId = SecurityContextUtil.getUserDetails().getId();
        String baseId = userService.findByUserId(userId).getBaseId();
        userService.deleteTypeInvitationRecord(baseId, typeId);
        return Result.success("删除成功");
    }

    /**
     * 用户删除所有基地的邀请
     *
     * @return
     */
    @ApiOperation("用户删除所有基地的邀请")
    @DeleteMapping("/deleteAllInvitation")
    public Result deleteAllInvitation() {
        String userId = SecurityContextUtil.getUserDetails().getId();
        userService.deleteAllInvitation(userId);
        return Result.success("删除成功");
    }

    /**
     * 用户删除指定基地的邀请
     *
     * @param baseId
     * @return
     */
    @ApiOperation("用户删除指定基地的邀请")
    @DeleteMapping("/deleteAllInvitation/{baseId}")
    public Result deleteInvitationByBaseId(@ApiParam(name = "baseId", value = "基地ID", required = true) @PathVariable(value = "baseId", required = true) String baseId) {
        String userId = SecurityContextUtil.getUserDetails().getId();
        userService.deleteInvitationByBaseId(userId, baseId);
        return Result.success("删除成功");
    }

//    /**
//     * 通过baseId查询基地内的所有用户
//     *
//     * @return
//     */
//    @ApiOperation(value = "查询基地内的所有用户")
//    @PreAuthorize("hasAnyAuthority('authority_user_select')")
//    @RequestMapping(value = "/getBaseUsers/{page}/{size}", method = RequestMethod.GET)
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "page", value = "页面", dataType = "Integer"),
//            @ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
//    })
//    public Result getUserByBaseId(@PathVariable Integer page, @PathVariable Integer size) {
//        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
//        //传入老板id查询基地用户
//        List<User> users = userService.getUsersByUserId(userDetails.getId());
//        PageResult<User> pageResult = PageUtil.getPage(users, page, size);
//        return new Result(true, StatusCode.OK, "获取成功", pageResult);
//    }

    /**
     * 老板更改用户在基地内的身份
     *
     * @param userId
     * @param baseIdentity
     * @return
     */
    @ApiOperation("老板更改用户在基地内的身份")
    @PreAuthorize("hasAnyAuthority('authority_role_update')")
    @RequestMapping(value = "/update/{userId}/{baseIdentity}", method = RequestMethod.PUT)
    public Result updateBaseRole(@PathVariable @Param("要修改的员工的id") String userId, @PathVariable Integer baseIdentity) {
        userService.updateBaseIdentityOfUser(userId, baseIdentity);
        return Result.success("修改角色成功");
    }

    /**
     * 分页查询基地人员信息（不包含自身）
     *
     * @param current
     * @param size
     * @return
     */
    @ApiOperation("分页查询基地人员信息")
    @GetMapping("/getBaseMember/{current}/{size}/{baseId}")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "current", value = "页面", dataType = "Integer"),
//            @ApiImplicitParam(paramType = "path", name = "size", value = "尺寸", dataType = "Integer")
//    })
    public Result pageBaseMember(@PathVariable(name = "current") Integer current,
                                 @PathVariable(name = "size") Integer size,
                                 @PathVariable String baseId) {
//        String userId = SecurityContextUtil.getUserDetails().getId();
//        String baseId = userService.findByUserId(userId).getBaseId();
//        if (baseId == null) {
//            return Result.error(StatusCode.ERROR, "查询失败");
//        }
//        List<User> baseMemberList = userService.getBaseMemberList(baseId, userId);
        List<User> baseMemberList = userService.findBaseMemberByBaseId(baseId);
        size = size <= 0 ? 5 : size;
        current = current <= 0 ? 1 : current;
        return Result.success("查询成功").data(PageUtil.getPage(baseMemberList, current, size));
    }

    /**
     * 查询基地人员信息（不包含自身）
     *
     * @return
     */
    @ApiOperation("查询基地人员信息")
    @GetMapping("/getBaseMember/{baseId}")
    public Result pageBaseMember(@PathVariable String baseId) {
//        String userId = SecurityContextUtil.getUserDetails().getId();
//        String baseId = userService.findByUserId(userId).getBaseId();
//        if (baseId == null) {
//            return Result.error(StatusCode.ERROR, "查询失败");
//        }
//        List<User> baseMemberList = userService.getBaseMemberList(userId, baseId);
//        return Result.success("查询成功").data(baseMemberList);

        List<User> baseMemberByBaseId = userService.findBaseMemberByBaseId(baseId);
        if(baseMemberByBaseId.equals(null)) {
            return Result.error("查无此基地");
        }
        return Result.success("").data(baseMemberByBaseId);
    }


    /**
     * 查询基地人员数量（不包含自身）
     *
     * @return
     */
    @ApiOperation("查询基地人员数量")
    @GetMapping("/getBaseMemberCount/{baseId}")
    public Result pageBaseMemberCount(@PathVariable String baseId) {
//        String userId = SecurityContextUtil.getUserDetails().getId();
//        String baseId = userService.findByUserId(userId).getBaseId();
//        if (baseId == null) {
//            return Result.error(StatusCode.ERROR, "查询失败");
//        }
//        List<User> baseMemberList = userService.getBaseMemberList(userId, baseId);
        List<User> baseMemberList = userService.findBaseMemberByBaseId(baseId);
        long total = baseMemberList.size();
        return Result.success("查询成功").data(total);
    }

    /**
     * 基地解雇员工
     *
     * @param userId
     * @return
     */
    @ApiOperation("基地解雇员工")
    @PutMapping("/sack/{userId}")
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", dataType = "String")
    @PreAuthorize("hasAnyAuthority('enterprise_enterprise_user')")
    public Result sackBaseMember(@PathVariable(name = "userId") String userId) {
        String uid = SecurityContextUtil.getUserDetails().getId();
        User user = userService.findByUserId(uid);
        String baseId = user.getBaseId();
        Integer baseIdentity = user.getBaseIdentity();
        userService.sackEmployeeByUserIdAndBaseId(userId, baseId, baseIdentity);
        return Result.success("解雇成功");
    }
}

